package com.mimo.logic.session.service.impl;

import java.time.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mimo.common.configuration.broadcast.MultiCastRegistry;
import com.mimo.common.configuration.mrlock.annotation.DistributedRedisLock;
import com.mimo.logic.event.UserStatusActionEvent;
import com.mimo.logic.event.UserStatusActionType;
import com.mimo.logic.session.constants.SessionKeys;
import com.mimo.logic.session.service.ISessionScheduleService;
import com.mimo.logic.session.service.ISessionService;
import com.mimo.logic.user.service.IUserService;

@Service
public class SessionScheduleServiceImpl implements ISessionScheduleService {

  private static final Logger log = LoggerFactory.getLogger(SessionScheduleServiceImpl.class);

  @Autowired
  private IUserService userService;

  @Autowired
  private ISessionService sessionService;

  @Override
  @DistributedRedisLock(key = SessionKeys.LOGIC_SESSION_SCHEDULE_CLEAR_KEY, expired = 60, waited = 60)
  public void clear(Duration expired, long count) {
    long end = System.currentTimeMillis() - expired.toMillis();
    sessionService.getByLastAccessTimeBetween(-1, end, count).forEach(uid -> {
      log.warn("user session[{}] 过期", uid);
      try {
        // offline时需要强制comet中断connection
        MultiCastRegistry.INSTANCE
            .publish(new UserStatusActionEvent(this, userService.load(uid), UserStatusActionType.Offline));
      } catch (Exception e) {
        log.error("", e);
      }
    });
  }

}
